package com.juyu.miliao.api.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.api.constant.DepositType;
import com.juyu.miliao.api.dao.mysql.BillDetailDao;
import com.juyu.miliao.api.dao.mysql.ChatSpendDao;
import com.juyu.miliao.api.dao.mysql.UserCountDao;
import com.juyu.miliao.api.dao.mysql.UserInfoDao;
import com.juyu.miliao.api.dao.mysql.UserWalletDao;
import com.juyu.miliao.api.dao.redis.CallTimeRedisDao;
import com.juyu.miliao.api.dao.redis.ChatSpendRedisDao;
import com.juyu.miliao.api.dao.redis.DiamondRedisDao;
import com.juyu.miliao.api.dao.redis.UserRedisDao;
import com.juyu.miliao.api.domain.*;
import com.juyu.miliao.api.handler.IntegralRewardsAndPunishmentsHandler;
import com.juyu.miliao.api.util.CallTimeUtil;
import com.juyu.miliao.api.handler.UserInvitationIncomeDetailsHandler;
import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.netease.NetEaseCloudUserService;
import com.juyu.miliao.common.redis.UserCallTimeRedis;
import com.juyu.miliao.common.util.DoubleFormatUtil;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;

import static com.juyu.miliao.common.msg.CommonErrorMsgs.CHATNO_DEPOSIT;

@Service
public class ChatSpendService {
    private final Logger logger = LoggerFactory.getLogger("chatSpendRoomId");
    @Resource
    private ChatSpendDao chatSpendDao;
    @Resource
    private UserInfoDao userInfoDao;
    @Resource
    private UserWalletDao userWalletDao;
    @Resource
    private BillDetailDao billDetailDao;
    @Resource
    private UserCountDao userCountDao;
    @Resource
    private ChatSpendRedisDao chatSpendRedisDao;
    @Resource
    private UserRedisDao userRedisDao;
    @Resource
    private IntegralLevelInfoService integralLevelInfoService;
    @Resource
    private CallTimeRedisDao callTimeRedisDao;
    @Resource
    private DiamondRedisDao diamondRedisDao;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IntegralRewardsAndPunishmentsHandler integralRewardsAndPunishmentsHandler;

    @Resource
    private UserInvitationIncomeDetailsHandler userInvitationIncomeDetailsHandler;
    @Resource
    private AppKeyService appKeyService;
    @Resource
    private UserCallService userCallService;

    private static final long  EXAMINE_IOS_USER_PROD = 389870700;
    private static final long  EXAMINE_IOS_USER_TEST = 10008301;

    /**
     * 1.5.4每分钟计费
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject chatSpendMinuteByServer(ChatSpend entity, CommonHead com){
        JSONObject json = new JSONObject();
        Appkey appkey = appKeyService.getAppKeyByKey("spendNoDepositTime");
        int spendNoDepositTime = Integer.parseInt(appkey.getValue());
        if(entity.getCallUserId()==EXAMINE_IOS_USER_PROD
                || entity.getAnswerUserId() == EXAMINE_IOS_USER_PROD
                ||entity.getCallUserId()==EXAMINE_IOS_USER_TEST
                || entity.getAnswerUserId() == EXAMINE_IOS_USER_TEST){
            json.put("deposit",0);
            json.put("spendNoDepositTime",spendNoDepositTime);
            json.put("isNoDepositPopup",false);
            json.put("popupTime",0);
            return json;
        }
        //计算发送方钱包金额是否够用
        UserWallet callUserWallet = userWalletDao.getUserWalletById(entity.getCallUserId());
        //获取接收方聊价
        User answerUser = userInfoDao.getUserInfoById(entity.getAnswerUserId());
        int recordSpend = Integer.parseInt(answerUser.getVideoPrice());
        //账号金额不足,关闭聊天房间
        if (callUserWallet.getDeposit() < recordSpend){
            try {
                int returnCode = NetEaseCloudUserService.deleteRoom(entity.getRoomId());
                if(returnCode != 200){
                    if(logger.isErrorEnabled()){
                        logger.error("用户金币不足,关闭房间云信异常：" + returnCode + "\n" + "参数：" + entity.toString());
                    }
                }else{
                    logger.info("用户金币不足关闭房间,云信结果："+returnCode);
                    logger.info("用户金币不足关闭房间,用户信息："+entity.toString());
                }
            }catch (Exception e){
                logger.error("用户金币不足,关闭房间异常！！",e);
            }
            throw new ConsumeRuntimeException(CHATNO_DEPOSIT);
        }
        //1.5.6是否是房间的第一次通话计费
        boolean firstCall = false;
        if(entity.getRoomId()!=null && !entity.getRoomId().equals("")){
            //获取计费次数
            Long chatSpendNum = chatSpendRedisDao.getListSizeByChatSpendRoomId(entity.getRoomId());
            if(chatSpendNum == null || chatSpendNum <= 0){
                //首次计费
                chatSpendRedisDao.addChatSpendRoomId(entity.getRoomId());
                firstCall = true;
                logger.info("开始首次计费------"+entity.toString());
            }else{
                //判断上次计费是否在50秒之内，如果在则抛弃该次计费
                String lastTimeSecond = chatSpendRedisDao.getEndDataByChatSpendRoomId(entity.getRoomId());
                long nowTimeSecond = Instant.now().getEpochSecond();
                if((nowTimeSecond-Long.parseLong(lastTimeSecond)) < 50){
                    logger.info("上次计费不足50秒------"+entity.toString()+"------"+com.toString()
                            +"------nowTimeSecond::::::"+nowTimeSecond+"------lastTimeSecond::::::"+lastTimeSecond);
                    throw new ConsumeRuntimeException("上次计费不足50秒");
                }
                chatSpendRedisDao.addChatSpendRoomId(entity.getRoomId());
                logger.info("正常计费------"+entity.toString()+"------chatSpendNum::::::"+chatSpendNum);
            }
        }else{
            logger.info("roomId为空,不执行计费校验逻辑------"+entity.toString()+"------"+com.toString());
        }

        //用于返回前端 发送方剩余金币
        int deposit = callUserWallet.getDeposit() - recordSpend;
        BigDecimal diamondConversionRate =integralLevelInfoService
                .getDiamondConversionRate(entity.getAnswerUserId());
        //是否够下一次计费,不够则弹窗
        boolean isNoDepositPopup = callUserWallet.getDeposit() < (recordSpend*2);
        //判断聊价是否为0
        if (recordSpend != 0) {
            //修改发送方钱包金额
            callUserWallet.setDeposit(recordSpend);
            userWalletDao.minusDeposit(callUserWallet);
            if(!firstCall){
                //修改接收方钱包钻石
                UserWallet answerUserWallet = new UserWallet();
                answerUserWallet.setUserId(entity.getAnswerUserId());
                // 获取礼物转换钻石比例
                answerUserWallet.setDiamond(DoubleFormatUtil.doubleFormate(diamondConversionRate.doubleValue()* recordSpend));
                userWalletDao.reviseDiamond(answerUserWallet);
                userCountDao.updateVideoDiamond(entity.getAnswerUserId(),answerUserWallet.getDiamond());
            }
        }
        //保存通话记录
        entity.setSpend(recordSpend);
        if(firstCall){
            entity.setDiamond(0);
            entity.setTalkTime("00:01");
        }else{
            entity.setDiamond(DoubleFormatUtil.doubleFormate(diamondConversionRate.doubleValue() * recordSpend));
            entity.setTalkTime("01:00");
        }
        chatSpendDao.insertChatSpend(entity);

        //维护主播繁忙状态1.5.6
        userCallService.userCallInfo(1,entity.getAnswerUserId());
        json.put("deposit",deposit);
        json.put("spendNoDepositTime",spendNoDepositTime);
        json.put("isNoDepositPopup",isNoDepositPopup);
        if(isNoDepositPopup){
            json.put("popupTime",60-spendNoDepositTime);
        }else{
            json.put("popupTime",0);
        }
        //返回发送方剩余金币
        return json;
    }

    /**
     * 1.5.4 总计计费
     * 通过mq消息抄送触发
     */
    @Transactional(rollbackFor = Exception.class)
    public void chatSpendEndByServer(String json) {
        logger.info("音频时长消息抄送参数---{}",json);
        if (json == null || json.isEmpty()) {
            if(logger.isInfoEnabled()){
                logger.info("音频时长消息抄送rabbitMQ抄送请求错误, json为空!");
            }
            return;
        }
        //{"duration":"298","ext":"extra_data","createtime":"1566205989891","
        // members":"[{\"duration\":149,\"accid\":\"142756600\",\"userType\":1},
        // {\"duration\":149,\"caller\":true,\"accid\":\"478455300\",\"userType\":1}]",
        // "eventType":"5","type":"VEDIO","channelId":"51321437849565","live":"0","status":"SUCCESS"}
        JSONObject jsStr = JSONObject.parseObject(json);
        //	类型：AUDIO：表示音频通话；VEDIO：表示视频通话；DataTunnel：表示白板事件
        String type = jsStr.get("type").toString();
        //通话/白板状态：SUCCESS：表示正常挂断；TIMEOUT：表示超时；
        // SINGLE_PARTICIPATE：表示只有一个参与者；UNKNOWN：表示未知状态
        String status = jsStr.get("status").toString();
        int duration = jsStr.getIntValue("duration"); //此通通话的通话时长，精确到秒
        JSONArray membersArray = JSONObject.parseArray(jsStr.get("members").toString());
        if(!type.equals("VEDIO") || !status.equals("SUCCESS") || duration<=0 || membersArray.size() < 2){
            logger.info("参数错误::::::type-"+type+",status-"+status
                    +",duration-"+duration+",membersArray-"+membersArray);
            return;
        }
        //2019-09-03审核帐号不计费
        String unknownUserIdOne = membersArray.getJSONObject(0).get("accid").toString();
        String unknownUserIdTwo = membersArray.getJSONObject(1).get("accid").toString();
        if(Long.parseLong(unknownUserIdOne)==EXAMINE_IOS_USER_PROD
                || Long.parseLong(unknownUserIdTwo)==EXAMINE_IOS_USER_PROD
                ||Long.parseLong(unknownUserIdOne)==EXAMINE_IOS_USER_TEST
                || Long.parseLong(unknownUserIdTwo)==EXAMINE_IOS_USER_TEST){
            logger.info("审核帐号通话不计费::::::json="+json);
            return;
        }
        String channelId = jsStr.get("channelId").toString(); //房间号
        int onceDuration = duration/2;//单方通话时长
        //1.5.2 需求 通话5秒不计算
//        if(onceDuration<=5){
//            logger.info("房间号"+channelId+",通话时长："+onceDuration+"---不足5秒");
//            return;
//        }
        // 1.根据 caller 区分谁扣钱，谁收钱
        User answerUser = new User();//赚钱用户
        User callUser = new User();//扣费用户
        User unknownUserOne = userInfoDao.getUserInfoById(Long.parseLong(unknownUserIdOne));
        User unknownUserTwo = userInfoDao.getUserInfoById(Long.parseLong(unknownUserIdTwo));
        if(unknownUserOne.getIsHost()==1 && unknownUserTwo.getIsHost()==2){
            answerUser = unknownUserOne;
            callUser = unknownUserTwo;
        }else if(unknownUserOne.getIsHost()==2 && unknownUserTwo.getIsHost()==1){
            answerUser = unknownUserTwo;
            callUser = unknownUserOne;
        }else{
            logger.info("房间内用户身份异常::::::unknownUserIdOne="+unknownUserIdOne
                    +",unknownUserOneIsHost="+unknownUserOne.getIsHost()
                    +",unknownUserIdTwo："+unknownUserIdTwo
                    +",unknownUserTwoIsHost="+unknownUserTwo.getIsHost());
            return;
        }
        //获取接收方聊价
        int recordSpend = Integer.parseInt(answerUser.getVideoPrice());
        Appkey appkey = appKeyService.getAppKeyByKey("callTimeSpendIgnore");
        int callTimeSpendIgnore = Integer.parseInt(appkey.getValue());
        //判断聊价是否为0
        if (recordSpend != 0) {
            if(onceDuration > callTimeSpendIgnore){
                //修改接收方钱包钻石
                UserWallet answerUserWallet = new UserWallet();
                answerUserWallet.setUserId(answerUser.getUserId());
                // 获取礼物转换钻石比例
                BigDecimal diamondConversionRate =integralLevelInfoService
                        .getDiamondConversionRate(answerUser.getUserId());
                answerUserWallet.setDiamond(DoubleFormatUtil.
                        doubleFormate(diamondConversionRate.doubleValue()* recordSpend));
                userWalletDao.reviseDiamond(answerUserWallet);
                userCountDao.updateVideoDiamond(answerUser.getUserId(),answerUserWallet.getDiamond());
            }
            //1.5.2 需求 通话5秒不计算 1.5.6废弃
            //minute应该计费次数
            int minute = (onceDuration) / 60;
            if ((onceDuration) % 60 > 0)
                minute = minute + 1;
            //获取实际计费次数
            Long chatSpendNum = chatSpendRedisDao.getListSizeByChatSpendRoomId(channelId);
            //补扣金币数
            int resultSpend = 0;
            //2. 少扣
            if((minute - chatSpendNum) > 0){
                resultSpend = chatSpendRepairDeduction(minute,chatSpendNum,recordSpend,
                        callUser.getUserId(),answerUser.getUserId());
            }
            //实际共扣金币数
            int spend = chatSpendNum.intValue() * recordSpend + resultSpend;
            //3. 计时、账单不准-使用云信同步视频时长时间为准生成账单
            BigDecimal diamondConversionRate =integralLevelInfoService
                    .getDiamondConversionRate(answerUser.getUserId());
            //保存消费记录
            BillDetailDeposit billDetailDeposit = new BillDetailDeposit();
            billDetailDeposit.setRecordType(3);
            billDetailDeposit.setInUserId(answerUser.getUserId());
            billDetailDeposit.setOutUserId(callUser.getUserId());
            billDetailDeposit.setSpend(-spend);
            if(onceDuration > callTimeSpendIgnore){
                billDetailDeposit.setDiamond(DoubleFormatUtil.doubleFormate(diamondConversionRate.doubleValue() * spend));
            }else{
                billDetailDeposit.setDiamond(0);
            }

            billDetailDeposit.setRatio(DoubleFormatUtil.doubleFormate(diamondConversionRate.doubleValue()));
            User inUser =  userInfoDao.selectAdminByUnionId(answerUser.getUserId());
            if(inUser !=null){
                billDetailDeposit.setAdminId(inUser.getAdminId());
                billDetailDeposit.setUnionId(inUser.getUnionId());
                billDetailDeposit.setAgentId(inUser.getAgentId());
            }
            billDetailDao.insertBillDetailDeposit(billDetailDeposit);

            //生成聊天结束界面账单
            JSONObject detailJson = new JSONObject();
            detailJson.put("roomId",channelId);
            detailJson.put("callUserId",callUser.getUserId());
            detailJson.put("answerUserId",answerUser.getUserId());
            detailJson.put("onceDurationSecond",onceDuration);
            detailJson.put("callTime", CallTimeUtil.secondToTime(onceDuration));
            detailJson.put("spend",billDetailDeposit.getSpend());
            detailJson.put("diamond",billDetailDeposit.getDiamond());
            detailJson.put("callTimeSpendIgnore",appkey.getValue());
            chatSpendRedisDao.addCallDetailRecord(channelId,detailJson);
            //4. 排行榜、后台数据支持
            callTimeRedisDao.setRankingList(LocalDate.now(),onceDuration,answerUser.getUserId()+"");
            //钻石排行榜统计主赚取钻石
            if(onceDuration > callTimeSpendIgnore){
                diamondRedisDao.setRankingDiamondList(LocalDate.now(),
                        DoubleFormatUtil.doubleFormate(diamondConversionRate.doubleValue()* spend),answerUser.getUserId()+"");

                integralRewardsAndPunishmentsHandler.diamondsForIntegralBy100(answerUser.getUserId(),
                        billDetailDeposit.getDiamond());
                //邀请钻石分成
                userInvitationIncomeDetailsHandler.incomeDiamondsDetails(answerUser.getUserId(), DepositType.CALL_VIDEO.getCode(),
                        new BigDecimal(billDetailDeposit.getDiamond()+""));
                //1.5.6主播每小时钻石收益
                diamondRedisDao.setHomeListIncomeByHostUser(answerUser.getUserId(),billDetailDeposit.getDiamond());
            }
            integralRewardsAndPunishmentsHandler.aSigleCallLastsMoreThanThreeMinutes(answerUser.getUserId(),minute);
            UserCallTimeRedis userCallTimeRedis = new UserCallTimeRedis(stringRedisTemplate);
            userCallTimeRedis.setUserCallTimes(answerUser.getUserId(),minute);
            userCallTimeRedis.setUserLastCallTime(answerUser.getUserId());
        }
        //维护主播繁忙状态1.5.6
        userCallService.userCallInfo(2,answerUser.getUserId());

        /**
         * redis存储打电话用户的id 和接通电话的主播id
         *
         */
        if(answerUser.getIsCertificationHost()==1){
            if(userRedisDao.getUserConnectAnchorShiPin(answerUser.getUserId()).size()<=80){
                long l = userRedisDao.userConnectAnchorShiPin(callUser.getUserId(), answerUser.getUserId());
                if(l>0){
                    userCountDao.addCallSuccessSumVedio(answerUser.getUserId());
                }
            }else {
                userCountDao.addCallSuccessSumVedio(answerUser.getUserId());
            }
        }

    }

    /**
     * 1.3 补充扣款
     * @param minute 应该扣款次数
     * @param chatSpendNum 实际当前扣款次数
     * @param recordSpend 每次扣款价格
     * @param callUserId 拨打用户id-花钱
     * @param answerUserId 接听用户id-赚钱
     */
    private int chatSpendRepairDeduction(int minute,Long chatSpendNum,int recordSpend,
                                          long callUserId,long answerUserId){
        //需要补扣的金币数量
        int spend = (int)(minute-chatSpendNum) * recordSpend;
        //获取用户钱包余额
        UserWallet callUserWallet = userWalletDao.getUserWalletById(callUserId);
        //钱包余额
        int surplus = callUserWallet.getDeposit();
        //实际扣款金币
        int resultSpend = surplus;
        //实际增加钻石
        double diamond = 0;
        if(surplus > 0){
            if(surplus - spend > 0){
                resultSpend = spend;
            }
            //修改发送方钱包金额
            callUserWallet.setUserId(callUserId);
            callUserWallet.setDeposit(resultSpend);
            userWalletDao.minusDeposit(callUserWallet);
            //修改接收方钱包钻石
            UserWallet answerUserWallet = new UserWallet();
            answerUserWallet.setUserId(answerUserId);
            BigDecimal diamondConversionRate =integralLevelInfoService
                    .getDiamondConversionRate(answerUserId);
            diamond = DoubleFormatUtil.doubleFormate(diamondConversionRate.doubleValue() * resultSpend);
            answerUserWallet.setDiamond(diamond);
            userWalletDao.reviseDiamond(answerUserWallet);
            userCountDao.updateVideoDiamond(answerUserId,diamond);
        }
        if(logger.isInfoEnabled()){
            logger.info("补扣聊天计费----扣款用户id:"+callUserId+",赚钻石用户id:"+answerUserId);
            logger.info("实际计费次数："+chatSpendNum+",聊天应扣次数："+minute);
            logger.info("漏扣次数："+(minute-chatSpendNum)+",聊天价格："+recordSpend+",应补扣金币："+spend);
            logger.info("实际补扣金币："+resultSpend+",实际补加钻石："+diamond);
        }
        return resultSpend;
    }

    public String getCallDetailRecord(String roomId) {
        if(roomId==null || roomId.equals("")){
            return null;
        }
        return chatSpendRedisDao.getCallDetailRecord(roomId);
    }


//    /**
//     * 每分钟计算聊天扣费
//     */
//    @Transactional(rollbackFor = Exception.class)
//    public int chatSpendMinute(ChatSpend entity, CommonHead com) {
//        //花蜜1.3聊天计费漏扣问题
//        chatSpendCounter(entity.getCallUserId(),entity.getAnswerUserId());
//        //计算发送方钱包金额是否够用
//        UserWallet callUserWallet = userWalletDao.getUserWalletById(entity.getCallUserId());
//        //1.5.2 聊天计费多扣问题
//        if(entity.getRoomId()!=null && !entity.getRoomId().equals("")
//                    && entity.getCallNum()>0){
//            logger.info("开始执行多扣逻辑校验--chatSpend::"+entity.toString());
//            String temp = chatSpendRedisDao.getRoomIdCallNum(entity.getRoomId());
//            if(temp==null || temp.equals("") || temp.equals("null") || temp.equals("0")){
//                logger.info("正常计费--callNum::"+temp);
//                chatSpendRedisDao.setRoomIdCallNum(entity.getRoomId());
//            }else{
//                int callNum = Integer.parseInt(temp);
//                if(entity.getCallNum()<=callNum){
//                    logger.info("重复计费--callNum::"+callNum+"--com::"+com.toString());
//                    return callUserWallet.getDeposit();
//                }else{
//                    logger.info("正常计费--callNum::"+callNum);
//                    chatSpendRedisDao.setRoomIdCallNum(entity.getRoomId());
//                }
//            }
//        }else{
//            logger.info("参数有误--忽略多扣校验逻辑**roomId::"+entity.getRoomId()+"**callNum::"+entity.getCallNum());
//        }
//        //获取接收方聊价
//        User answerUser = userInfoDao.getUserInfoById(entity.getAnswerUserId());
//        int recordSpend = 0;
//        //聊天类型：1 语音 2视频
//        if (entity.getRecordType() == 1)
//            recordSpend = Integer.parseInt(answerUser.getChatPrice());
//        else {
//            recordSpend = Integer.parseInt(answerUser.getVideoPrice());
//        }
//
//        if (callUserWallet.getDeposit() < recordSpend)
//            throw new ConsumeRuntimeException(CHATNO_DEPOSIT);
//        //用于返回前端 发送方剩余金币
//        int deposit = callUserWallet.getDeposit() - recordSpend;
////        Appkey appkey = appkeyService.getAppKeyByKey("giftRatio");
//        BigDecimal diamondConversionRate =integralLevelInfoService
//                .getDiamondConversionRate(entity.getAnswerUserId());
//        //判断聊价是否为0
//        if (recordSpend != 0) {
//            //修改发送方钱包金额
//            callUserWallet.setDeposit(recordSpend);
//            userWalletDao.minusDeposit(callUserWallet);
//            //修改接收方钱包钻石
//            UserWallet answerUserWallet = new UserWallet();
//            answerUserWallet.setUserId(entity.getAnswerUserId());
//            // 获取礼物转换钻石比例
//            answerUserWallet.setDiamond(DoubleFormatUtil.doubleFormate(diamondConversionRate.doubleValue()* recordSpend));
//            userWalletDao.reviseDiamond(answerUserWallet);
//            userCountDao.updateVideoDiamond(entity.getAnswerUserId(),answerUserWallet.getDiamond());
//        }
//        //保存通话记录
//        entity.setSpend(recordSpend);
//        entity.setDiamond(DoubleFormatUtil.doubleFormate(diamondConversionRate.doubleValue() * recordSpend));
//        entity.setTalkTime("01:00");
//        chatSpendDao.insertChatSpend(entity);
//        //返回发送方剩余金币
//        return deposit;
//    }

//    /**
//     * 聊天扣费计数器
//     * @param callUserId 拨打用户id-花钱
//     * @param answerUserId 接通用户id-赚钱
//     */
//    private void chatSpendCounter(int callUserId,int answerUserId){
//        chatSpendRedisDao.chatSpendCounter(callUserId+"-"+answerUserId);
//    }


//    /**
//     * 总计
//     * @param entity
//     * @param appPackageId
//     * @param phone
//     * @param version
//     */
//    @Transactional(rollbackFor = Exception.class)
//    public void chatSpendEnd(ChatSpend entity,String appPackageId, String phone,String version) {
//        //1.5.2 需求 通话5秒不计算
//        if(entity.getCallTime()<=5){
//            logger.info("房间号"+entity.getRoomId()+",通话时长："+entity.getCallTime()+"---不足5秒");
//            return;
//        }
//        if(entity.getRoomId()!=null && !entity.getRoomId().equals("")){
//            if(chatSpendRedisDao.isMemberRoomId(entity.getRoomId())){
//                if(logger.isErrorEnabled()){
//                    logger.error("房间号"+entity.getRoomId()+"已存在");
//                    logger.error("参数:appPackageId={},phone={},version={}",appPackageId,phone,version);
//                }
//                throw new ConsumeRuntimeException("房间号"+entity.getRoomId()+"已存在");
//            }
//            chatSpendRedisDao.setRoomId(entity.getRoomId());
//        }
//        //获取接收方聊价
//        User answerUser = userInfoDao.getUserInfoById(entity.getAnswerUserId());
//        int recordSpend = 0;
//        //聊天类型：1 语音 2视频
//        if (entity.getRecordType() == 1)
//            recordSpend = Integer.parseInt(answerUser.getChatPrice());
//        else {
//            recordSpend = Integer.parseInt(answerUser.getVideoPrice());
//        }
//        //1.5.2 需求 通话5秒不计算
//        entity.setCallTime(entity.getCallTime()-5);
//        int minute = (int) (entity.getCallTime() / 60);
//        if (entity.getCallTime() % 60 > 0)
//            minute = minute + 1;
//        //判断聊价是否为0
//        if (recordSpend != 0) {
////            Appkey appkey = appkeyService.getAppKeyByKey("giftRatio");
//            BigDecimal diamondConversionRate =integralLevelInfoService
//                    .getDiamondConversionRate(entity.getAnswerUserId());
//            //保存消费记录
////            BillDetail billDetail = new BillDetail();
//            // 消费类型： 2 语音聊天 3 视频聊天
//            //聊天类型：1 语音 2视频
////            if (entity.getRecordType() == 1)
////                billDetail.setRecordType(2);
////            else {
////                billDetail.setRecordType(3);
////            }
////            billDetail.setInUserId(entity.getAnswerUserId());
////            billDetail.setOutUserId(entity.getCallUserId());
////            billDetail.setDiamond(DoubleFormatUtil.doubleFormate(Double.parseDouble(appkey.getValue()) * recordSpend * minute));
////            billDetail.setSpend(minute * recordSpend);
////            billDetailDao.insertBillDetail(billDetail);
////            //用户统计m值
////            userCountDao.addMGradeSum(entity.getAnswerUserId(), billDetail.getDiamond());
////            //排行榜统计
////            redisTemplateService.setMUserSort(entity.getAnswerUserId(), billDetail.getDiamond());
////            redisTemplateService.setTUserSort(entity.getAnswerUserId(),entity.getCallTime());
//            BillDetailDeposit billDetailDeposit = new BillDetailDeposit();
//            billDetailDeposit.setRecordType(3);
//            billDetailDeposit.setInUserId(entity.getAnswerUserId());
//            billDetailDeposit.setOutUserId(entity.getCallUserId());
//            billDetailDeposit.setSpend(-(minute * recordSpend));
//            billDetailDeposit.setDiamond(DoubleFormatUtil.doubleFormate(diamondConversionRate.doubleValue()* recordSpend * minute));
//            billDetailDeposit.setRatio(DoubleFormatUtil.doubleFormate(diamondConversionRate.doubleValue()));
//            User inUser =  userInfoDao.selectAdminByUnionId(entity.getAnswerUserId());
//
//            if(inUser !=null){
//                billDetailDeposit.setAdminId(inUser.getAdminId());
//                billDetailDeposit.setUnionId(inUser.getUnionId());
//                billDetailDeposit.setAgentId(inUser.getAgentId());
//            }
//
//            billDetailDao.insertBillDetailDeposit(billDetailDeposit);
//
//            callTimeRedisDao.setRankingList(LocalDate.now(),entity.getCallTime(),entity.getAnswerUserId()+"");
//            //钻石排行榜统计主赚取钻石
//            diamondRedisDao.setRankingDiamondList(LocalDate.now(),
//                    DoubleFormatUtil.doubleFormate(diamondConversionRate.doubleValue()* recordSpend * minute),entity.getAnswerUserId()+"");
//
//            integralRewardsAndPunishmentsHandler.aSigleCallLastsMoreThanThreeMinutes(entity.getAnswerUserId(),minute);
//
//            integralRewardsAndPunishmentsHandler.diamondsForIntegralBy100(entity.getAnswerUserId(),
//                    billDetailDeposit.getDiamond());
//
//            UserCallTimeRedis userCallTimeRedis = new UserCallTimeRedis(stringRedisTemplate);
//
//            userCallTimeRedis.setUserCallTimes(entity.getAnswerUserId(),minute);
//
//            userCallTimeRedis.setUserLastCallTime(entity.getAnswerUserId());
//            //补充扣款
//            chatSpendRepairDeduction(minute,recordSpend,entity.getCallUserId(),entity.getAnswerUserId());
//        }
//        /**
//         * redisc存储打电话用户的id 和接通电话的主播id
//         *
//         */
//        if(answerUser.getIsCertificationHost()==1){
//            if(entity.getRecordType()==1){
//                //如果接通语音人数小于10人 主播id 和 拨打语音的用户id 存入redis中 语音人数+1
//                if(userRedisDao.getUserConnectAnchorYuYin(entity.getAnswerUserId()).size()<=30){
//                    long l = userRedisDao.userConnectAnchorYuYin(entity.getCallUserId(), entity.getAnswerUserId());
//                    if(l>0){
//                        userCountDao.addCallSuccessSumVoice(entity.getAnswerUserId());
//                    }
//
//                }else {
//                    userCountDao.addCallSuccessSumVoice(entity.getAnswerUserId());
//                }
//            }else if(entity.getRecordType()==2){
//                if(userRedisDao.getUserConnectAnchorShiPin(entity.getAnswerUserId()).size()<=80){
//                    long l = userRedisDao.userConnectAnchorShiPin(entity.getCallUserId(), entity.getAnswerUserId());
//                    if(l>0){
//                        userCountDao.addCallSuccessSumVedio(entity.getAnswerUserId());
//                    }
//                }else {
//                    userCountDao.addCallSuccessSumVedio(entity.getAnswerUserId());
//                }
//
//            }
//        }
//    }

}
